import type {  SelectorInfo, ApiParams, OptionField } from "./type.ts";
import { ref } from "vue";
import api from "@/utils/api";
import { message } from "ant-design-vue";

// 创建独立的服务实例
export const createSelectorService = (config: {
    apiPath: string;
    apiParams: ApiParams;
    modalName: string;
    optionField: OptionField;
}) => {
    const fetching = ref(false);
    const selectorInfo = ref<SelectorInfo>({
        index: -1,
        desc: undefined,
        option: [],
    });
    const newName = ref<string>();

    const reset = () => {
        selectorInfo.value = {
            index: -1,
            desc: undefined,
            option: [],
        };
    };

    // 获取列表
    const fetch = async (searchValue: string, masterValue?: string) => {
        try {
            fetching.value = true;
            const searchRef=ref<any>(searchValue);
            if(config.apiParams.searchKey==='NA'){
                searchRef.value=undefined;
            }
            const masterRef=ref<any>(masterValue);
            if(config.apiParams.masterKey==='NA'){
                masterRef.value=undefined;
            }
            const response = await api.get(config.apiPath, {
                params: {
                    [config.apiParams.searchKey]: searchRef.value,
                    [config.apiParams.masterKey]: masterRef.value,
                }
            });
            selectorInfo.value.option = response.data;
            if (searchValue && searchValue.length > 0) {
                newName.value = searchValue;
            }
        } catch (error) {
            message.error(`获取${config.modalName}列表失败`);
            console.error(`获取${config.modalName}列表失败:`, error);
        } finally {
            fetching.value = false;
        }
    };

    // 搜索方法
    const onSearch = async (searchValue: string, masterValue?: string) => {
        await fetch(searchValue, masterValue);
    };

    const onFocus = async (masterValue?: string) => {
        await fetch(selectorInfo.value.desc||'', masterValue);
    };

    // 选择变化
    const onChange = (value: string) => {
        const foundItem = selectorInfo.value.option.find(s =>
            s[config.optionField.value] === value
        );

        if (foundItem) {
            selectorInfo.value.index = foundItem[config.optionField.key];
            selectorInfo.value.desc = foundItem[config.optionField.value];
            selectorInfo.value.entity=foundItem;
        } else {
            selectorInfo.value.desc = newName.value || value;
            selectorInfo.value.index = undefined;
        }
        newName.value = undefined;
    };

    const onBlur = () => {
        if (newName.value) {
            onChange(newName.value);
        }
    };

    return {
        fetching,
        selectorInfo,
        reset,
        onSearch,
        onFocus,
        onBlur,
        onChange,
    };
};